<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by xiaobai at 2023/3/1 18:14
 */

namespace Cmslz\HyperfTenancy\Kernel\Resource\Src;


use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Resource\Response\PaginatedResponse;
use Hyperf\Codec\Json;
use Hyperf\Collection\Collection;
use Psr\Http\Message\ResponseInterface;

class PaginatedResourceResponse extends PaginatedResponse
{
    public function toResponse(): ResponseInterface
    {
        $paginated = $this->resource->resource->toArray();
        return $this->response()
            ->withStatus($this->calculateStatus())
            ->withAddedHeader('content-type', 'application/json; charset=utf-8')
            ->withBody(
                new SwooleStream(
                    Json::encode(
                        $this->wrap(
                            [
                                'data' => [
                                    'data' => $this->resource->resolve(),
                                    "current_page" => $paginated['current_page'] ?? null,
                                    "total" => $paginated['total'] ?? null
                                ]
                            ],
                            array_merge_recursive(
                                $this->paginationInformation(),
                                $this->resource->with(),
                                $this->resource->additional
                            )
                        )
                    )
                )
            );
    }

    protected function paginationInformation():array
    {
        return [];
    }

    protected function wrap(array|Collection $data, array $with = [], array $additional = []): array
    {
        return parent::wrap(
            array_merge(
                [
                    'code' => 0,
                    'message' => 'success',
                ],
                $data
            ),
            $with,
            $additional
        ); // TODO: Change the autogenerated stub
    }
}